package com.zjzywl.smoke.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLDecoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.websocket.server.PathParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.zjzywl.smoke.config.AppConfig;
import com.zjzywl.smoke.entity.Picture;
import com.zjzywl.smoke.entity.ThreeColorWarning;
import com.zjzywl.smoke.util.WebResult;

@Controller
@RequestMapping(value = "/threeColor")
public class ThreeColorWarningController extends BaseController {

    @Autowired
    private AppConfig appConfig;

    /*
     * 新建三色卡
     */
    @PostMapping(value = "/save/{orgId}")
    @ResponseBody
    public WebResult save(@RequestBody ThreeColorWarning tcw, @PathVariable("orgId") Integer orgId) {
        ResponseEntity<ThreeColorWarning> newtcw = appConfig.restTemplate()
                .postForEntity(appConfig.getGetDataIp() + "/threeColor/save/" + orgId, tcw, ThreeColorWarning.class);
        return WebResult.OK(newtcw);
    }

    @InitBinder
    public void initBinder(ServletRequestDataBinder binder) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
        binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
    }

    /*
     * 多图片上传
     */
    @RequestMapping("/upload")
    public @ResponseBody WebResult uploads(HttpServletRequest request, @PathParam("uuid") String uuid,
            @PathParam("onlyValue") String onlyValue, MultipartFile[] multipartFile)
            throws IllegalStateException, IOException {
        HttpHeaders headers = new HttpHeaders();
        try {
            for (MultipartFile jarFile : multipartFile) {
                String tempFileName = UUID.randomUUID()
                        + jarFile.getOriginalFilename().substring(jarFile.getOriginalFilename().lastIndexOf("."));
                String tempFilePath = getUploadDir() + tempFileName;
                File tempFile = new File(tempFilePath);
                jarFile.transferTo(tempFile);

                FileSystemResource fileSystemResource = new FileSystemResource(tempFilePath);
                MediaType type = MediaType.parseMediaType("multipart/form-data");
                headers.setContentType(type);
                String cd = "filename=\"" + jarFile.getOriginalFilename() + "\"";
                headers.add("Content-Disposition", cd);
                MultiValueMap<String, Object> form = new LinkedMultiValueMap<String, Object>();
                form.add("file", fileSystemResource);
                HttpEntity<MultiValueMap<String, Object>> files = new HttpEntity<>(form, headers);
                ResponseEntity<String> responseEntity = null;
                responseEntity = appConfig.restTemplate().postForEntity(
                        appConfig.getGetDataIp() + "/threeColor/upload?uuid=" + uuid + "&onlyValue=" + onlyValue, files,
                        String.class);

                tempFile.delete();
            }
            return WebResult.OK("图片上传成功");
        } catch (Exception e) {
            return WebResult.FAIL(e.toString());
        }
    }

    /*
     * 获取图片id列表
     */
    @RequestMapping("/getList")
    public @ResponseBody WebResult getPictuceList(@PathParam("uuid") String uuid) {
        try {
            ResponseEntity<Object> findByUuid = appConfig.restTemplate()
                    .getForEntity(appConfig.getGetDataIp() + "/threeColor/getList?uuid=" + uuid, Object.class);
            return WebResult.OK(findByUuid);
        } catch (Exception e) {
            return WebResult.FAIL("图片列表获取失败");
        }

    }

    /*
     * 获得照片，根据id
     */
    @RequestMapping(value = "/getImg", method = RequestMethod.GET)
    @ResponseBody
    public void doGetBackgroundImg(@PathParam("id") Integer id, HttpServletResponse response) throws Exception {
        Picture cp = appConfig.restTemplate().getForObject(appConfig.getGetDataIp() + "/threeColor/getPicture?id=" + id,
                Picture.class);
        String pictureFile = cp.getFile();
        response.setContentType("image/jpeg ");
        FileInputStream fis = new FileInputStream(pictureFile);
        OutputStream os = response.getOutputStream();
        try {
            int count = 0;
            byte[] buffer = new byte[1024 * 1024];

            while ((count = fis.read(buffer)) != -1) {
                os.write(buffer, 0, count);
            }

            os.flush();
        } catch (Exception e) {
            System.out.println("获取图片出错" + e);
        } finally {
            if (os != null)
                os.close();
            if (fis != null)
                fis.close();
        }
    }

    /*
     * 获取三色卡片
     */
    @RequestMapping(value = "/getInfo", method = RequestMethod.GET)
    @ResponseBody
    public WebResult getThreeColorWarning(HttpServletRequest request) throws Exception {
        try {
            String userId = this.getUserId();
            ResponseEntity<Object> findByUuid = appConfig.restTemplate()
                    .getForEntity(appConfig.getGetDataIp() + "/threeColor/getInfo?userId=" + userId + "&"
                            + URLDecoder.decode(request.getQueryString(), "utf-8"), Object.class);
            return WebResult.OK(findByUuid);

        } catch (Exception e) {
            return WebResult.FAIL("获取三色卡片失败");
        }
    }

    /*
     * 删除图片，根据id
     * 
     */
    @DeleteMapping(value = "/delPicture")
    @ResponseBody
    public WebResult delThreeColorWarningPicture(@PathParam("id") Integer id) throws Exception {
        try {
            appConfig.restTemplate().delete(appConfig.getGetDataIp() + "/threeColor/delPicture?id=" + id);
            return WebResult.OK();
        } catch (Exception e) {
            return WebResult.FAIL(e.toString());
        }
    }

    /*
     * 删除三色卡片，根据id
     * 
     */
    @DeleteMapping(value = "/del")
    @ResponseBody
    public WebResult delThreeColorWarning(@PathParam("onlyValue") String onlyValue) throws Exception {
        try {
            appConfig.restTemplate().delete(appConfig.getGetDataIp() + "/threeColor/del?onlyValue=" + onlyValue);
            return WebResult.OK();
        } catch (Exception e) {
            return WebResult.FAIL(e.toString());
        }
    }

    /*
     * 获取单个三色预警场所下的所有三色预警卡片
     */
    @RequestMapping(value = "/getByOnlyValue", method = RequestMethod.GET)
    @ResponseBody
    public WebResult getByOnlyValue(@RequestParam(value = "onlyValue", required = false) String onlyValue)
            throws Exception {
        try {
            ResponseEntity<Object> findByUuid = appConfig.restTemplate().getForEntity(
                    appConfig.getGetDataIp() + "/threeColor/getByOnlyValue?onlyValue=" + onlyValue, Object.class);
            return WebResult.OK(findByUuid);
        } catch (Exception e) {
            return WebResult.FAIL(e.toString());
        }
    }

    /*
     * 获取三色预警场所占比
     */
    @RequestMapping(value = "/getThreeColorWarningProportion", method = RequestMethod.GET)
    @ResponseBody
    public WebResult getThreeColorWarningProportion() throws Exception {
        try {
            String userId = this.getUserId();
            ResponseEntity<Object> object = appConfig.restTemplate().getForEntity(
                    appConfig.getGetDataIp() + "/threeColor/getThreeColorWarningProportion?userId=" + userId,
                    Object.class);
            return WebResult.OK(object);
        } catch (Exception e) {
            return WebResult.FAIL(e.toString());
        }
    }

    /*
     * 获取三色卡片（加入整改）
     */
    @RequestMapping(value = "/getRectifyInfo", method = RequestMethod.GET)
    @ResponseBody
    public WebResult getRectifyThreeColorWarning(HttpServletRequest request) throws Exception {
        String userId = this.getUserId();
        ResponseEntity<Object> object = appConfig.restTemplate()
                .getForEntity(appConfig.getGetDataIp() + "/threeColor/getRectifyInfo?userId=" + userId + "&"
                        + URLDecoder.decode(request.getQueryString(), "utf-8"), Object.class);
        return WebResult.OK(object);

    }

    // 获取 整改详情接口
    @RequestMapping(value = "/getRectifyByOnlyValue", method = RequestMethod.GET)
    @ResponseBody
    public WebResult getRectifyByOnlyValue(@RequestParam(value = "onlyValue", required = false) String onlyValue)
            throws Exception {
        ResponseEntity<Object> object = appConfig.restTemplate().getForEntity(
                appConfig.getGetDataIp() + "/threeColor/getRectifyByOnlyValue?onlyValue=" + onlyValue, Object.class);
        return WebResult.OK(object);
    }

    /*
     * 获取单个三色预警场所(单个)
     */
    @RequestMapping(value = "/getThreeColorWarning", method = RequestMethod.GET)
    @ResponseBody
    public WebResult getThreeColorWarning(@RequestParam(value = "onlyValue", required = false) String onlyValue)
            throws Exception {
        ResponseEntity<Object> object = appConfig.restTemplate().getForEntity(
                appConfig.getGetDataIp() + "/threeColor/getThreeColorWarning?onlyValue=" + onlyValue, Object.class);
        return WebResult.OK(object);
    }

    // 整改成效图
    @RequestMapping("/getThreeColorWarningRectifyProportion")
    @ResponseBody
    public WebResult getThreeColorWarningRectifyProportion() {
        String userId = this.getUserId();
        ResponseEntity<Object> object = appConfig.restTemplate().getForEntity(
                appConfig.getGetDataIp() + "/threeColor/getThreeColorWarningRectifyProportion?userId=" + userId,
                Object.class);
        return WebResult.OK(object);
    }
}
